/**
 *
 * 提供上传图片、视频、音频等指令
 */
define(function (require, exports, module) {
    var angular = require('angular');

    require('/static_public/node_modules/angular-file-upload/angular-file-upload');

    var module = angular.module('angularFileUpload');
    module.service('nvFileUploadService',[
        '$rootScope',
        'FileUploader',
        'apife',
        'apibe',
        function ($rootScope,FileUploader,apife,apibe) {
            this.createFileUploader = function (options) {
                return new FileUploader({
                    url: apife + apibe + options.api,
                    filters: options.filters || [],
                    alias: 'file',
                    formData: options.data,
                    autoUpload: true,
                    removeAfterUpload: true,
                    onBeforeUploadItem : function(fileItem){
                        if(options.onBeforeUploadItem) {
                            options.onBeforeUploadItem(fileItem);
                        }else{
                            $rootScope.$emit('httpRequestStart','正在上传');
                        }
                    },
                    onCompleteItem: function (item, res) {
                        if (res.result || res.retCode == 0) {
                            options.success && options.success(res);
                            $rootScope.$emit('httpRequestEnd');
                            $rootScope.$emit('httpRequestFail','上传成功');
                            return;
                        }
                        if(options.fail){
                            options.fail(res);
                        }else{
                            $rootScope.$emit('httpRequestFail','上传失败');
                        }
                    },
                    onErrorItem: function (item,res) {
                        if(options.fail){
                            options.fail(res);
                        }else{
                            $rootScope.$emit('httpRequestFail','上传失败');
                        }
                    },
                    onWhenAddingFileFailed: function (item,filter) {
                        if(options.error) {
                            options.error(filter.name);
                        }
                    }
                });
            };
            this.getImageUploader = function(options){
                return this.createFileUploader({
                    api : 'upload/upload-image',
                    filters: [
                        {
                            name: 'sizeLimit',
                            fn: function (item) {
                                return item.size <= 2 * 1024 * 1024;
                            }
                        }
                    ],
                    error: function (item,filter) {
                        if (filter.name === "sizeLimit"){
                            alert('请选择2M以内的图片文件');
                        }
                    },
                    success : function(res){
                        options.success&&options.success(res);
                    }
                });
            }
            this.getImageGroupUploader = function(options){
                return this.createFileUploader({
                    api : 'material/upload',
                    filters: [
                        {
                            name: 'sizeLimit',
                            fn: function (item) {
                                return item.size <= 2 * 1024 * 1024;
                            }
                        }
                    ],
                    data : [{type : 'picture'}],
                    error: function (item,filter) {
                        if (filter.name === "sizeLimit"){
                            alert('请选择2M以内的图片文件');
                        }
                    },
                    onBeforeUploadItem : function(fileItem){
                        fileItem.formData.push({
                            group_id : options.getGroupId ? options.getGroupId() : ''
                        });
                    },
                    success : function(res){
                        options.success&&options.success(res);
                    }
                });
            }
            this.getVoiceUploader = function(options){
                return this.createFileUploader({
                    api: "material/upload",
                    data: [{type:'voice'}],
                    filters:[
                        {
                            name: 'voiceFilter',
                            fn: function (item) {
                                return /\.(mp3|wma|wav|amr)$/.test(item.name);
                            }
                        },{
                            name: 'sizeLimit',
                            fn: function (item) {
                                return item.size <= 5 * 1024 * 1024;
                            }
                        }
                    ],
                    success: function (res) {
                        options.success&&options.success(res);
                    },
                    error: function (filter) {
                        if (filter === "voiceFilter") {
                            alert('请上传正确的音频文件');
                        } else if (filter === "sizeLimit"){
                            alert('请选择5M以内的音频文件');
                        }
                    }
                })
            }

            this.getVideoUploader = function(options){
                return this.createFileUploader({
                    api: "upload/upload-file",
                    filters:[
                        {
                            name: 'videoFilter',
                            fn: function (item) {
                                return /\.(mp4|rm|rmvb|avi|mpeg|mpg)$/.test(item.name);
                            }
                        },{
                            name: 'sizeLimit',
                            fn: function (item) {
                                return item.size <= 20 * 1024 * 1024;
                            }
                        }
                    ],
                    success: function (res) {
                        options.success&&options.success(res);
                    },
                    error: function (filter) {
                        if (filter === "videoFilter") {
                            alert('请上传正确的视频文件');
                        } else if (filter === "sizeLimit"){
                            alert('请选择20M以内的视频文件');
                        }
                    }
                })
            }
            /**
             *
             * @param type
             * @param callback
             * @returns {*}
             */
            this.getUpload = function(type ,callback){

                var upload,options = {
                    success : function(data){
                        callback && callback(data.data);
                    }
                };
                switch (type){
                    case 'image' :
                        upload = this.getImageUploader(options);
                        break;
                    case 'imageGroup' :
                        upload = this.getImageGroupUploader(options);
                        break;
                    case 'video' :
                        upload = this.getVideoUploader(options);
                        break;
                    case 'voice' :
                        upload = this.getVoiceUploader(options);
                        break;
                    default :
                        upload = this.createFileUploader(options);
                }
                return upload;
            }
        }
    ]);
    module.directive('nvFileUpload', ['$parse', 'FileUploader','nvFileUploadService',function($parse, FileUploader,nvFileUploadService) {
        return {
            link: function(scope, element, attributes) {

                var uploader = nvFileUploadService.getUpload(attributes.nvFileUpload,scope.$eval(attributes.nvFileCallback));

                if (!(uploader instanceof FileUploader)) {
                    throw new TypeError('"Uploader" must be an instance of FileUploader');
                }

                var object = new FileUploader.FileSelect({
                    uploader: uploader,
                    element: element
                });

                object.getOptions = $parse(attributes.options).bind(object, scope);
                object.getFilters = function() {return attributes.filters;};
            }
        };
    }])
})